import 'dart:io';

import 'package:flut/src/utils/file_utils.dart';

import '../constants/constants.dart';
import 'package:path/path.dart' as path;

import '../init/templates.dart';
import '../utils/utils.dart';

/// The generator of localization files.
class GeneratorAssets {
  late String _className;
  late String _mainLocale;
  late String _arbDir;
  late String _outputDir;
  late bool _useDeferredLoading;
  List<String> body = [];

  /// Creates a new generator with configuration from the 'pubspec.yaml' file.
  GeneratorAssets() {
    _className = defaultClassName;
    _mainLocale = defaultMainLocale;
    _arbDir = defaultArbDir;
    _outputDir = defaultOutputDir;
    _useDeferredLoading = defaultUseDeferredLoading;
    // if (pubspecConfig.outputDir != null) {
    //   if (isValidPath(pubspecConfig.outputDir!)) {
    //     _outputDir = pubspecConfig.outputDir!;
    //   } else {
    //     warning(
    //         "Config parameter 'output_dir' requires valid path value (e.g. 'lib', 'lib\\generated').");
    //   }
    // }
  }

  /// Generates localization files.
  Future<void> generateAsync() async {
    await _readAssetsFolder();
    await _generateAssets();
  }

  Future<void> _readAssetsFolder() async {
    var rootDirPath = getRootDirectoryPath();
    var assetsFolder = path.join(rootDirPath, 'assets');
    List<String> list = [];
    _folderList(list, assetsFolder);
    for (var i = 0; i < list.length; i++) {
      final imgPath = list[i].replaceAll('$rootDirPath/', '');
      final splits = imgPath.split('/').reversed.take(2).toList();
      // print('file $imgPath $splits');
      if (splits.length == 2) {
        final name = '${_camelCase(splits[1])}${_camelCase(splits[0], upperCase: true)}';
        // print('name: $name ${path.withoutExtension(name)}');
        // static const String imagesIcDel = 'assets/images/ic_del.png';
        body.add('  static const String ${path.withoutExtension(name)} = \'$imgPath\';');
      }
    }
  }

  Future<void> _generateAssets() async {
    /// /lib/genated/assets.dart
    final outputDir = path.join(getRootDirectoryPath(), _outputDir, 'assets.dart');
    final content = generateAssets(body.join('\n'));
    final formattedContent = formatDartContent(content, 'assets.dart');
    await updateDartFile(formattedContent, outputDir);
  }

  String _camelCase(String name, {bool upperCase = false}) {
    final re = RegExp(r'[-_]');
    final splits = name.split(re);
    // print('_camelCase $splits');
    final result = splits.map((e) => '${e[0].toUpperCase()}${e.substring(1)}').join('');
    if (upperCase) {
      return result;
    } else {
      return '${result[0].toLowerCase()}${result.substring(1)}';
    }
  }

  void _folderList(List<String> list, String folder) {
    final filesAndDirectories = Directory(folder).listSync();
    for (var entity in filesAndDirectories) {
      if (entity is File) {
        list.add(entity.absolute.path);
      } else if (entity is Directory) {
        _folderList(list, entity.absolute.path);
      }
    }
  }
}
